package com.xh.bussiness.practice.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.bussiness.exam.model.UserErrorQuestion;
import com.xh.bussiness.exam.service.IUserErrorQuestionService;
import com.xh.bussiness.exam.service.impl.UserErrorQuestionServiceImpl;
import com.xh.bussiness.practice.bean.dto.*;
import com.xh.bussiness.practice.bean.request.CorrectPracticeStudentRequest;
import com.xh.bussiness.practice.bean.request.PracticeStudentRequest;
import com.xh.bussiness.practice.bean.request.PracticeStudentResultRequest;
import com.xh.bussiness.practice.constant.PracticeConstant;
import com.xh.bussiness.practice.model.Practice;
import com.xh.bussiness.practice.model.PracticeDetail;
import com.xh.bussiness.practice.model.PracticeStudent;
import com.xh.bussiness.practice.dao.PracticeStudentMapper;
import com.xh.bussiness.practice.model.PracticeStudentResult;
import com.xh.bussiness.practice.service.IPracticeDetailService;
import com.xh.bussiness.practice.service.IPracticeService;
import com.xh.bussiness.practice.service.IPracticeStudentResultService;
import com.xh.bussiness.practice.service.IPracticeStudentService;
import com.xh.bussiness.system.model.Dictionary;
import com.xh.bussiness.system.service.IDictionaryService;
import com.xh.bussiness.system.service.IParentStudentService;
import com.xh.bussiness.tiku.bean.dto.AnswerResultDto;
import com.xh.bussiness.tiku.bean.dto.QuestionDto;
import com.xh.bussiness.tiku.constant.QuestionConstant;
import com.xh.bussiness.tiku.model.Question;
import com.xh.bussiness.tiku.service.IPaperQuestionService;
import com.xh.bussiness.tiku.service.IPaperService;
import com.xh.bussiness.tiku.service.IQuestionService;
import com.xh.bussiness.tiku.service.IQuestionTypeRelationService;
import com.xh.bussiness.tiku.util.CheckQuestionUtil;
import com.xh.core.exception.XhException;
import com.xh.core.service.impl.BaseServiceImpl;
import com.xh.core.util.DateUtils;
import com.xh.core.util.MathUtils;
import com.xh.tools.question.constant.QuestionTypeEnum;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xh.core.bean.XhPage;
import com.xh.core.util.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 学生作业表 服务实现类
 * </p>
 *
 * @author Pitt
 * @since 2021-01-26
 */
@Service
public class PracticeStudentServiceImpl extends BaseServiceImpl<PracticeStudentMapper, PracticeStudent> implements IPracticeStudentService {

    @Autowired
    private IPracticeService practiceService;
    @Autowired
    private IPracticeStudentResultService practiceStudentResultService;
    @Autowired
    private IQuestionService questionService;
    @Autowired
    private IPaperQuestionService paperQuestionService;
    @Autowired
    private IPaperService paperService;
    @Autowired
    private IDictionaryService dictionaryService;
    @Autowired
    private IParentStudentService practiceStudentService;
    @Autowired
    private IPracticeDetailService practiceDetailService;
    @Autowired
    private IUserErrorQuestionService errorQuestionService;


    @Override
    public XhPage queryPracticeStudentPage(XhPage page, PracticeStudentRequest bean) {
        QueryWrapper qw = new QueryWrapper<PracticeStudent>();
        //拼装条件
        qw = prepareParams(bean, qw);

        return (XhPage) this.dao.selectPage(page, qw);
    }

    @Override
    public List queryPracticeStudent(PracticeStudentRequest bean) {
        QueryWrapper<PracticeStudent> qw = new QueryWrapper<PracticeStudent>();
        //拼装条件
        qw = prepareParams(bean, qw);

        List<PracticeStudent> list = this.dao.selectList(qw);
        if (!CollectionUtils.isEmpty(list)) {
            for (PracticeStudent practiceStudent : list) {
                String practiceId = practiceStudent.getPracticeId();
                Practice practice = practiceService.getById(practiceId);
                if (!StringUtils.isEmpty(practice.getPaperId())) {
                    practiceStudent.setPaperScore(paperService.queryPaperScore(practice.getPaperId()));
                }
            }
        }
        return list;
    }

    @Override
    public void deleteByPracticeId(String practiceId) {
        this.dao.deleteByPracticeId(practiceId);
    }

    @Override
    public List<PracticeStudent> queryByPracticeId(String practiceId) {
        QueryWrapper qw = new QueryWrapper<PracticeStudent>();
        qw.eq("practice_id", practiceId);
//        qw.groupBy("student_id");
        return this.dao.selectList(qw);
    }

    @Override
    public XhPage queryPracticeStudentPageByStudentId(PracticeStudentRequest bean) {
        XhPage xhPage = new XhPage();
        xhPage.setCurrent(bean.getCurrent());
        xhPage.setSize(bean.getSize());
        xhPage = this.dao.queryPracticeStudentPage(xhPage, bean);
        if (CollectionUtils.isEmpty(xhPage.getRecords())) {
            return xhPage;
        }
        List<Map<String, Object>> practiceStudents = xhPage.getRecords();
        //按发布时间分组
        List<PracticeGroupByDateDto> resultList = new ArrayList<>();
        Map<String, List<Map<String, Object>>> practiceStudentGroupMaps = practiceStudents.stream().collect(Collectors.groupingBy(item -> item.get("createTime").toString()));
        //将时间进行排序
        List<String> dataList = new ArrayList<>(practiceStudentGroupMaps.keySet());
        List<Date> dateList = dataList.stream().map(item -> DateUtils.parse(item, "yyyy-MM-dd")).sorted(Comparator.reverseOrder()).collect(Collectors.toList());
        dateList.forEach(item -> {
            String k = DateUtils.format(item, "yyyy-MM-dd");
            List<Map<String, Object>> v = practiceStudentGroupMaps.get(k);
            if (!CollectionUtils.isEmpty(v)) {
                PracticeGroupByDateDto dateDto = new PracticeGroupByDateDto();
                dateDto.setPublishDate(k);
                List<PracticeStudentDto> dtos = new ArrayList<>();
                for (Map<String, Object> data : v) {
                    PracticeStudentDto dto = new PracticeStudentDto();
                    if (data != null) {
                        if (PracticeConstant.PRACTICE_TIKU.equals(Integer.valueOf(data.get("type").toString()))) {
                            dto.setQuestionCount(practiceStudentResultService.getPracticeQuestionCount(data.get("practiceId").toString(), bean.getStudentId()));
                        }
                        dto.setPracticeId(data.get("practiceId") == null ? "" : data.get("practiceId").toString());
                        dto.setPracticeName(data.get("title") == null ? "" : data.get("title").toString());
                        dto.setPracticeStudentId(data.get("id") == null ? "" : data.get("id").toString());
                        dto.setType(Integer.valueOf(data.get("type").toString()));
                        dto.setTitle(data.get("title") == null ? "" : data.get("title").toString());
                        dto.setStartTime(data.get("startTime") == null ? "" : data.get("startTime").toString());
                        dto.setEndTime(data.get("endTime") == null ? "" : data.get("endTime").toString());
                        dto.setPracticeCreateTime(data.get("practiceCreateTime") == null?"":data.get("practiceCreateTime").toString());
                        dto.setPublishTime(data.get("publishTime")==null?"":data.get("publishTime").toString());
                        dto.setClassNames(data.get("classNames") == null ? "" : data.get("classNames").toString());
                        dto.setStatus(Integer.valueOf(data.get("status").toString()));

                        dtos.add(dto);
                    }
                }
                if (!CollectionUtils.isEmpty(dtos)) {
                    dateDto.setPracticeStudentDtos(dtos);
                }
                resultList.add(dateDto);
            }
        });
        xhPage.setRecords(CollectionUtils.isEmpty(resultList) ? new ArrayList() : resultList);
        return xhPage;
    }

    @Override
    public List<PracticeStudentResultDTO> queryPracticeStudentDetail(String studentId, String practiceId) {
        Practice practice = practiceService.getById(practiceId);

        PracticeStudentResultRequest resultRequest = new PracticeStudentResultRequest();
        resultRequest.setStudentId(studentId);
        resultRequest.setPracticeId(practiceId);
        List<PracticeStudentResult> studentResults = practiceStudentResultService.queryPracticeStudentResult(resultRequest);
        if (CollectionUtils.isEmpty(studentResults)) {
            return new ArrayList<>();
        }
        List<PracticeStudentResultDTO> results = new ArrayList<>();
        studentResults.forEach(item -> {
            PracticeStudentResultDTO dto = new PracticeStudentResultDTO();
            BeanUtils.copyProperties(item, dto);
            if (practice.getType().equals(PracticeConstant.PRACTICE_TIKU) && !StringUtils.isEmpty(item.getQuestionId())) {

                if (!StringUtils.isEmpty(item.getAnswerContent())) {
                    dto.setAnswerContent(JSON.parseArray(item.getAnswerContent()));
                }
                QuestionDto question = questionService.getQuestion(item.getQuestionId(), null, true, false, false, false,false);
                if (question != null) {
                    question.setScore(paperQuestionService.queryQuestionScore(practice.getPaperId(), item.getQuestionId()));
                    dto.setQuestion(question);
                }
            }
            if (!StringUtils.isEmpty(dto.getFileUrl())) {
                dto.setFileUrls(Arrays.asList(dto.getFileUrl().split(",")));
            }
            results.add(dto);
        });
        return results;
    }

    @Override
    public void submitPracticeStudentResult(SubmitPracticeResultDto practiceResultDto) {
        PracticeStudent practiceStudent = this.getById(practiceResultDto.getStudentPracticeId());
        if (practiceStudent == null) {
            throw new XhException("学生作业不存在");
        }

        Practice practice = practiceService.getById(practiceStudent.getPracticeId());
        if (practice == null) {
            throw new XhException("作业不存在");
        }

        PracticeDto practiceDto = practiceService.queryPracticeDetailById(practiceStudent.getPracticeId());

        List<PracticeStudentResultDTO> practiceStudentResults = practiceResultDto.getPracticeStudentResults();
        //普通作业
        if (practiceDto.getType().equals(PracticeConstant.PRACTICE_COMMON)) {
            practiceStudentResultService.deleteByPracticeIdAndStuId(practiceStudent.getPracticeId(), practiceStudent.getStudentId());
            for (PracticeStudentResultDTO dto : practiceStudentResults) {
                PracticeStudentResult practiceStudentResult = new PracticeStudentResult();
                BeanUtils.copyProperties(dto, practiceStudentResult);
                if (dto.getAnswerContent() != null) {
                    practiceStudentResult.setAnswerContent(dto.getAnswerContent().toJSONString());
                }
                practiceStudentResult.setStudentId(practiceResultDto.getStudentId());
                practiceStudentResult.setPracticeId(practiceStudent.getPracticeId());
                practiceStudentResultService.insert(practiceStudentResult);
            }
//            practiceStudent.setStatus(1);
            practiceStudent.setStatus(practiceResultDto.getStatus());
        }
        else if (practiceDto.getType().equals(PracticeConstant.PRACTICE_TIKU)) {
            practiceStudentResultService.deleteByPracticeIdAndStuId(practiceStudent.getPracticeId(), practiceStudent.getStudentId());
            //题库作业
            List<PracticeStudentResult> results = new ArrayList<>();
            List<UserErrorQuestion> insertErrorQuestions = new ArrayList<>();//新增错题
            List<UserErrorQuestion> updateErrorQuestions = new ArrayList<>();//修改错题
            for (PracticeStudentResultDTO dto : practiceStudentResults) {
                PracticeStudentResult practiceStudentResult = new PracticeStudentResult();
                BeanUtils.copyProperties(dto, practiceStudentResult);
                if (dto.getAnswerContent() != null) {
                    practiceStudentResult.setAnswerContent(dto.getAnswerContent().toJSONString());
                }
                String questionId = practiceStudentResult.getQuestionId();
                if (!StringUtils.isEmpty(questionId)) {
                    Question question = questionService.getById(questionId);
                    if (question != null) {
                        Dictionary subject = dictionaryService.queryByCode(question.getSubjectId(), "SUBJECT");
                        AnswerResultDto answerResultDto = CheckQuestionUtil.checkAnswer(subject == null ? "" : subject.getName(), question.getBasicType(), question.getRightAnswer(), practiceStudentResult.getAnswerContent(), practiceStudentResult.getScore());
                        if (!CollectionUtils.isEmpty(practiceStudentResult.getFileUrls())) {
                            practiceStudentResult.setFileUrl(String.join(",", practiceStudentResult.getFileUrls()));
                        }
                        practiceStudentResult.setPracticeId(practiceStudent.getPracticeId());
                        practiceStudentResult.setStudentId(practiceStudent.getStudentId());
                        practiceStudentResult.setCorrect(answerResultDto.getResult());
                        practiceStudentResult.setScore(answerResultDto.getScore());

                        results.add(practiceStudentResult);

                        //将错题加入错题本
                        if(answerResultDto.getResult()==0){
                            List<String> classIds = Arrays.asList(practiceStudent.getClassId().split(","));
                            joinErrorQuestion(insertErrorQuestions,updateErrorQuestions,practiceStudentResult,question,classIds);
                        }
                    }
                }
            }
            practiceStudentResultService.batchInsert(results);
//            for (PracticeStudentResult result : results){
//                practiceStudentResultService.insert(result);
//            }
            errorQuestionService.batchInsert(insertErrorQuestions);
            errorQuestionService.batchUpdate(updateErrorQuestions);
            long count = results.stream().filter(item -> item.getCorrect().equals(QuestionConstant.ANSWER_RESULT.TEACHER_CORRECT)).count();
            if (count <= 0) {
                //将作业状态更改为已批改
                practiceStudent.setStatus(2);
            } else {
                practiceStudent.setStatus(1);
            }
        }
        practiceStudent.setSubmitTime(new Date());
//        practiceStudent.setStatus(practiceResultDto.getStatus());
        this.update(practiceStudent);

        //将作业状态更改为已提交
        practice.setStatus(3);
        practiceService.update(practice);
    }

    @Override
    public void modifyCorrectPracticeStudent(CorrectPracticeStudentRequest bean) {
        String studentPracticeId = bean.getStudentPracticeId();
        PracticeStudent practiceStudent = this.getById(studentPracticeId);
        if (practiceStudent == null) {
            throw new XhException("学生作业不存在");
        }
        List<UserErrorQuestion> insertErrorQuestions = new ArrayList<>();//新增错题
        List<UserErrorQuestion> updateErrorQuestions = new ArrayList<>();//修改错题
        List<String> classIds = Arrays.asList(practiceStudent.getClassId().split(","));
        for (PracticeStudentResult studentResult : bean.getStudentResults()) {
            practiceStudentResultService.update(studentResult);
            if(studentResult.getCorrect()==0){
                //错题加入错题本
                Question question = new Question();
                BeanUtils.copyProperties(studentResult.getQuestion(), question);
                joinErrorQuestion(insertErrorQuestions,updateErrorQuestions,studentResult,question,classIds);
            }

        }
        errorQuestionService.batchInsert(insertErrorQuestions);
        errorQuestionService.batchUpdate(updateErrorQuestions);
        practiceStudent.setStatus(2);
        this.update(practiceStudent);
    }

    @Override
    public PracticeStudentAnalyseDto queryPracticeStudentReport(String practiceId, String studentId) {
        QueryWrapper<PracticeStudent> qw = new QueryWrapper<>();
        qw.eq("practice_id", practiceId);
        qw.eq("student_id", studentId);

        PracticeStudent practiceStudent = this.selectFirst(qw);
        if (practiceStudent == null) {
            throw new XhException("学生作业不存在");
        }
        if (!practiceStudent.getStatus().equals(2)) {
            throw new XhException("学生作业未批改");
        }
        Practice practice = practiceService.getById(practiceId);
        if (practice == null) {
            throw new XhException("作业不存在");
        }
        // 普通作业没有作答报告
        if (practice.getType().equals(PracticeConstant.PRACTICE_COMMON)) {
            throw new XhException("非题库作业，暂不支持查看报告");
        }


        PracticeStudentResultRequest resultRequest = new PracticeStudentResultRequest();
        resultRequest.setStudentId(studentId);
        resultRequest.setPracticeId(practiceId);
        List<PracticeStudentResult> studentResults = practiceStudentResultService.queryPracticeStudentResult(resultRequest);
        if (CollectionUtils.isEmpty(studentResults)) {
            throw new XhException("学生作答结果不存在");
        }

        List<QuestionDto> questionDtos = new ArrayList<>();
        studentResults.forEach(item -> {
            QuestionDto question = questionService.getQuestion(item.getQuestionId(), null, true, false, false, false,false);
            if (question != null) {

                PracticeStudentResultDTO dto = new PracticeStudentResultDTO();
                BeanUtils.copyProperties(item, dto);
                if (!StringUtils.isEmpty(item.getAnswerContent())) {
                    dto.setAnswerContent(JSON.parseArray(item.getAnswerContent()));
                }
                if (!StringUtils.isEmpty(item.getFileUrl())) {
                    dto.setFileUrls(Arrays.asList(item.getFileUrl().split(",")));
                }
                question.setPracticeStudentResultDTO(dto);
                questionDtos.add(question);
            }
        });

        double score = studentResults.stream().mapToDouble(PracticeStudentResult::getScore).sum();

        Map<Integer, List<QuestionDto>> typeQuestions = questionDtos.stream().collect(Collectors.groupingBy(QuestionDto::getType));
        //主观题正确率
        List<QuestionAnalyseDto> subjectiveQuestionAnalysis = new ArrayList<>();
        //客观题正确率
        List<QuestionAnalyseDto> objectiveQuestionAnalysis = new ArrayList<>();
        typeQuestions.forEach((k, v) -> {
            if (!CollectionUtils.isEmpty(v)) {
                String questionTypeName = v.get(0).getQuestionTypeName();
                Integer basicQuestionType = v.get(0).getBasicQuestionType();
                //作答结果（-1未作答，0错误，1正确，2部分正确）
                long rightCount = v.stream().filter(item -> item.getPracticeStudentResultDTO().getCorrect().equals(1)).count();
                int totalCount = v.size();

                QuestionAnalyseDto dto = new QuestionAnalyseDto();
                dto.setQuestionTypeName(questionTypeName);
                dto.setRightQuestionCount(rightCount);
                dto.setTotalQuestionCount(totalCount);
                //获取客观题
                if (basicQuestionType.equals(QuestionTypeEnum.SINGLE.getValue())
                        || basicQuestionType.equals(QuestionTypeEnum.MUL.getValue())
                        || basicQuestionType.equals(QuestionTypeEnum.JUDGE.getValue())) {
                    objectiveQuestionAnalysis.add(dto);
                } else {
                    //主观题
                    subjectiveQuestionAnalysis.add(dto);
                }
            }
        });
        //主观题正确率
        Double subjectiveScoreRate = 0.0;
        //客观题正确率
        Double objectiveScoreRate = 0.0;

        if (!CollectionUtils.isEmpty(objectiveQuestionAnalysis)) {
            Integer totalQuestionCount = objectiveQuestionAnalysis.stream().mapToInt(QuestionAnalyseDto::getTotalQuestionCount).sum();
            Long rightQuestionCount = objectiveQuestionAnalysis.stream().mapToLong(QuestionAnalyseDto::getRightQuestionCount).sum();
            objectiveScoreRate = MathUtils.getNumberRate(MathUtils.divTwoNumberRoundHalfUp(rightQuestionCount, totalQuestionCount, MathUtils.DEFAULT_SCALE), MathUtils.DEFAULT_SCALE);
        }
        if (!CollectionUtils.isEmpty(subjectiveQuestionAnalysis)) {
            Integer totalQuestionCount = subjectiveQuestionAnalysis.stream().mapToInt(QuestionAnalyseDto::getTotalQuestionCount).sum();
            Long rightQuestionCount = subjectiveQuestionAnalysis.stream().mapToLong(QuestionAnalyseDto::getRightQuestionCount).sum();
            subjectiveScoreRate = MathUtils.getNumberRate(MathUtils.divTwoNumberRoundHalfUp(rightQuestionCount, totalQuestionCount, MathUtils.DEFAULT_SCALE), MathUtils.DEFAULT_SCALE);
        }

        //封装结果
        PracticeStudentAnalyseDto dto = new PracticeStudentAnalyseDto();
        dto.setPracticeId(practiceId);
        dto.setPracticeName(practice.getTitle());
        dto.setStudentId(practiceStudent.getStudentId());
        dto.setStudentName(practiceStudent.getStudentName());
        dto.setTotalScore(score);
        if (practiceStudent.getSubmitTime() != null) {
            dto.setSubmitTime(DateUtils.format(practiceStudent.getSubmitTime(), "yyyy-MM-dd HH:mm:ss"));
        }
        dto.setSubjectiveQuestionAnalysis(subjectiveQuestionAnalysis);
        dto.setSubjectiveScoreRate(subjectiveScoreRate);
        dto.setObjectiveQuestionAnalysis(objectiveQuestionAnalysis);
        dto.setObjectiveScoreRate(objectiveScoreRate);
        dto.setQuestionDtos(questionDtos);

        practiceStudent.setScore(score);
        if (!StringUtils.isEmpty(practice.getPaperId())) {
            dto.setPracticeScore(paperService.queryPaperScore(practice.getPaperId()));
        }

        this.update(practiceStudent);
        return dto;
    }


    @Override
    public PracticeStudentResultDetailDTO queryPracticeStudentResult(String practiceId, String studentId) {

        QueryWrapper<PracticeStudent> qw = new QueryWrapper<>();
        qw.eq("practice_id", practiceId);
        qw.eq("student_id", studentId);

        PracticeStudent practiceStudent = this.selectFirst(qw);
        if (practiceStudent == null) {
            throw new XhException("学生作业不存在");
        }
        Practice practice = practiceService.getById(practiceId);
        if (practice == null) {
            throw new XhException("作业不存在");
        }

        PracticeStudentResultRequest resultRequest = new PracticeStudentResultRequest();
        resultRequest.setStudentId(studentId);
        resultRequest.setPracticeId(practiceId);
        List<PracticeStudentResult> studentResults = practiceStudentResultService.queryPracticeStudentResult(resultRequest);
        if (CollectionUtils.isEmpty(studentResults)) {
            throw new XhException("学生作答结果不存在");
        }

        List<QuestionDto> questionDtos = new ArrayList<>();
        studentResults.forEach(item -> {
            QuestionDto question = questionService.getQuestion(item.getQuestionId(), null, true, false, false, false,false);
            if (question != null) {
                PracticeStudentResultDTO dto = new PracticeStudentResultDTO();
                BeanUtils.copyProperties(item, dto);
                if (!StringUtils.isEmpty(item.getAnswerContent())) {
                    dto.setAnswerContent(JSON.parseArray(item.getAnswerContent()));
                }
                question.setPracticeStudentResultDTO(dto);
                if (!StringUtils.isEmpty(item.getFileUrl())) {
                    dto.setFileUrls(Arrays.asList(item.getFileUrl().split(",")));
                }
                questionDtos.add(question);
            }
        });

        PracticeStudentResultDetailDTO detailDTO = new PracticeStudentResultDetailDTO();
        Map<String, Object> retMap = new HashMap<>();
        detailDTO.setPracticeId(practice.getId());
        detailDTO.setPracticeName(practice.getTitle());
        detailDTO.setStudentId(practiceStudent.getStudentId());
        detailDTO.setStudentName(practiceStudent.getStudentName());
        detailDTO.setSubmitTime(DateUtils.format(practiceStudent.getSubmitTime(), "yyyy-MM-dd HH:mm:ss"));
        detailDTO.setQuestionDtos(questionDtos);
        return detailDTO;
    }

    @Override
    public PracticeStudent commentStudentPractice(String practiceId, String studentId, double score, String comment) {
        QueryWrapper<PracticeStudent> qw = new QueryWrapper<>();
        qw.eq("practice_id",practiceId);
        qw.eq("student_id", studentId);
        PracticeStudent practiceStudent = selectFirst(qw);
        // 状态改为已批改
        practiceStudent.setStatus(2);
        practiceStudent.setScore(score);
        practiceStudent.setComment(comment);
        super.update(practiceStudent);
        return practiceStudent;
    }

    @Override
    public Map<String, Object> queryPracticeDetails(String practiceId, String studentId) {
        Practice practice = practiceService.getById(practiceId);
        QueryWrapper<PracticeStudent> qw = new QueryWrapper<>();
        qw.eq("practice_id",practiceId);
        qw.eq("student_id", studentId);
        PracticeStudent practiceStudent = selectFirst(qw);
        QueryWrapper<PracticeStudentResult> rsQw = new QueryWrapper<>();
        rsQw.eq("practice_id",practiceId);
        rsQw.eq("student_id", studentId);
        List<PracticeStudentResult> practiceStudentResults = practiceStudentResultService.queryByCondition(rsQw);
        QueryWrapper<PracticeDetail> pdQw = new QueryWrapper<>();
        pdQw.eq("practice_id",practiceId);
        List<PracticeDetail> practiceDetails = practiceDetailService.queryByCondition(pdQw);
        Map<String, Object> result = new HashMap<>();
        result.put("practice",practice);
        result.put("practiceDetails",practiceDetails);
        result.put("practiceStudent",practiceStudent);
        result.put("practiceStudentResults",practiceStudentResults);
        return result;
    }

    /**
     * 准备条件
     *
     * @param bean
     * @param qw
     */
    private QueryWrapper prepareParams(PracticeStudentRequest bean, QueryWrapper qw) {
        if (bean.getIds() != null && bean.getIds().length > 0) {
            qw.in("id", bean.getIds());
        }
        if (!StringUtils.isEmpty(bean.getStudentId())) {
            qw.eq("student_id", bean.getStudentId());
        }
        if (!StringUtils.isEmpty(bean.getStudentName())) {
            qw.like("student_name", bean.getStudentName());
        }
       /* if (bean.getType() != null) {
            qw.eq("type", bean.getType());
        }*/
        if (!StringUtils.isEmpty(bean.getPracticeId())) {
            qw.eq("practice_id", bean.getPracticeId());
        }
        if (bean.getStatus() != null) {
            //查已批改和已提价
            if (bean.getStatus().equals(3)) {
                qw.ne("status", 0);
            } else {
                qw.eq("status", bean.getStatus());
            }
        }
        if (!StringUtils.isEmpty(bean.getClassId())) {
            qw.eq("class_id", bean.getClassId());
        }
        if(bean.getClassIds()!=null && bean.getClassIds().size()>0){
            qw.in("class_id",bean.getClassIds());
        }
        if (!StringUtils.isEmpty(bean.getPublishMonth())) {
            qw.apply("date_format(create_time,'%Y-%m') = {0}", bean.getPublishMonth());
        }
        if (bean.getSort() == null) {
            qw.orderByDesc("create_time");
        } else if (bean.getSort().equals(1)) {
            //提交时间正序
            qw.orderByAsc("submit_time");
        } else {
            //提交时间倒序
            qw.orderByDesc("submit_time");
        }

        return qw;
    }

    /**
     * 查询普通作业合格率
     * @author 赵文博
     * @date 2021/4/23 13:49
     * @param practiceId
     * @return double
     **/
    @Override
    public double queryNormalQualified(String practiceId) {
        return this.dao.queryNormalQualified(practiceId);
    }

    /**
     * 查询普通作业优秀率
     * @author 赵文博
     * @date 2021/5/20 17:37
     * @param practiceId
     * @return double
     **/
    @Override
    public Double queryNormalProficiency(String practiceId) {
        return this.dao.queryNormalProficiency(practiceId);
    }

    /**
     * 错题加入错题本
     * @author 赵文博
     * @date 2021/5/8 17:16
     * @param userErrorQuestions
     * @param practiceStudentResult
     * @param question
     * @param classIds
     * @return void
     **/
    private void joinErrorQuestion( List<UserErrorQuestion> insertErrorQuestions,List<UserErrorQuestion> updateErrorQuestions,
                                    PracticeStudentResult practiceStudentResult,
                                    Question question,List<String> classIds){

        String questionId = practiceStudentResult.getQuestionId();
        String studentId = practiceStudentResult.getStudentId();
        for(String classId :classIds){
            QueryWrapper<UserErrorQuestion> qw = new QueryWrapper<>();
            qw.eq("question_id",questionId);
            qw.eq("student_id",studentId);
            qw.eq("class_id",classId);
            List<UserErrorQuestion> list = errorQuestionService.selectList(qw,UserErrorQuestion.class);
            if(list!=null && list.size()>0){
                UserErrorQuestion errorQuestion = list.get(0);
                Integer errorCount = errorQuestion.getErrorCount()+1;
                errorQuestion.setErrorCount(errorCount);
                updateErrorQuestions.add(errorQuestion);
            }else {
                UserErrorQuestion errorQuestion = new UserErrorQuestion();
                errorQuestion.setSubjectId(question.getSubjectId());
                errorQuestion.setQuestionId(questionId);
                errorQuestion.setQuestionVersion(question.getCurrentVersion());
                errorQuestion.setQuestionSource("作业");
                errorQuestion.setSourceType(4);
                errorQuestion.setStudentId(studentId);
                errorQuestion.setErrorCount(1);
                errorQuestion.setClassId(classId);
                errorQuestion.setPracticeId(practiceStudentResult.getPracticeId());
                errorQuestion.setLessonType(1);//班课
                insertErrorQuestions.add(errorQuestion);
            }
        }

    }

    @Override
    public List<PracticeStudent> queryPracticeStudentStatusCount(String practiceId) {
        return this.dao.queryPracticeStudentStatusCount(practiceId);
    }
}
